package com.etoak.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.etoak.common.core.exception.CustomException;
import com.etoak.common.core.properties.ImageProperties;
import com.etoak.common.core.vo.ResultVO;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/upload")
public class UploadController {

    /**
     * common-web => common-jwt => common-core
     */
    @Autowired
    ImageProperties imageProperties;

    /**
     * 假设: 前端 当前这个接口 【el-upload name="pic"】
     */
    @PostMapping("/image")
    public ResultVO<String> uploadImage(MultipartFile pic) {
        // 1 判断是否是空
        if (ObjectUtils.isEmpty(pic) || pic.isEmpty()) {
            throw new CustomException("文件不允许是空");
        }

        // 2 判断文件的类型 【Content-Type】
        String contentType = pic.getContentType();
        if (!imageProperties.getTypeList().contains(contentType)) {
            String types = imageProperties.getTypeList().stream()
                .map(x -> x.split("/")[1])
                .collect(Collectors.joining("，"));
            throw new CustomException("仅允许" + types + "类型的文件");
        }

        // 3 创建上传目录
        String location = imageProperties.getLocation();
        File parent = new File(location);
        if (!parent.exists()) {
            parent.mkdirs();
        }

        // 4 创建上传的文件名称
        // uuid.png
        String originalFilename = pic.getOriginalFilename();
        String fileName = IdUtil.simpleUUID() +
            originalFilename.substring(originalFilename.lastIndexOf(StrUtil.DOT));

        File target = new File(parent, fileName);

        // 5 上传
        try {
            pic.transferTo(target);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 6 返回
        // /pics/uuid.png
        String result = imageProperties.getPrefix().endsWith(StrUtil.SLASH) ?
            imageProperties.getPrefix() + fileName :
            imageProperties.getPrefix() + StrUtil.SLASH + fileName;

        return ResultVO.success(result);
    }
}
